package com.loadburn.heron.complier.tags;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.mvel2.MVEL;
import org.mvel2.integration.VariableResolverFactory;
import org.mvel2.templates.TemplateRuntime;
import org.mvel2.templates.res.ExpressionNode;
import org.mvel2.templates.res.Node;
import org.mvel2.templates.util.TemplateOutputStream;
import org.mvel2.util.ParseTools;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 13-12-26
 */
public class HasAnyPermissionNode extends Node {

    private static final long serialVersionUID = 2812866030232601679L;
    protected static final String PERMISSION_NAMES_SPLIT = ",";

    protected Node trueNode;
    protected Node elseNode;

    public HasAnyPermissionNode(int begin, String name, char[] template, int start, int end) {
        super(begin, name, template, start, end);
        while (cEnd > cStart && ParseTools.isWhitespace(template[cEnd])) cEnd--;
    }

    public Node getTrueNode() {
        return trueNode;
    }

    public void setTrueNode(ExpressionNode trueNode) {
        this.trueNode = trueNode;
    }

    public Node getElseNode() {
        return elseNode;
    }

    public void setElseNode(ExpressionNode elseNode) {
        this.elseNode = elseNode;
    }

    @Override
    public boolean demarcate(Node terminatingNode, char[] template) {
        trueNode = next;
        next = terminus;
        return true;
    }

    @Override
    public Object eval(TemplateRuntime runtime, TemplateOutputStream appender, Object ctx, VariableResolverFactory factory) {

        boolean hasAnyPermission = false;
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            String permissionNames = MVEL.eval(contents, cStart, cEnd - cStart, ctx, factory, String.class);
            for (String permission : permissionNames.split(PERMISSION_NAMES_SPLIT)) {
                if (subject.isPermitted(permission.trim())) {
                    hasAnyPermission = true;
                    break;
                }
            }
        }
        if (cEnd == cStart || hasAnyPermission) {
            return trueNode.eval(runtime, appender, ctx, factory);
        }

        return next != null ? next.eval(runtime, appender, ctx, factory) : null;
    }

}
